package codeTop;

public class q142 {
    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode pre = new ListNode();
        pre.next  = head;
        ListNode fast = pre;
        ListNode slow = pre;
        while (fast != null&&fast.next!=null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                break;
            }
        }
        if (fast == null||fast.next==null) {
            return null;
        }
        slow = pre;
        while (slow!=fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}
